package org.arch_learn.rpc.nz_rpc.quartz;

import org.apache.curator.framework.CuratorFramework;
import org.arch_learn.rpc.nz_rpc.endpoint.NettyRpcClient;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Enumeration;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class ScheduledJob extends QuartzJobBean {

    //定时任务处理逻辑：刷新注册到zk上的服务提供实例节点上面的请求时间和请求时长
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        JobDataMap jobDataMap = jobExecutionContext.getJobDetail().getJobDataMap();
        Object object = jobDataMap.get("client");
        Object clientsMapObj = jobDataMap.get("nettyRpcClientsMap");

        CuratorFramework curatorClient = (CuratorFramework) object;
        ConcurrentHashMap<String, List<NettyRpcClient>> clientsMap = (ConcurrentHashMap<String, List<NettyRpcClient>>) clientsMapObj;
        //这个代表没有可以使用的服务提供者上线，这样就无须处理了。
        if (clientsMap.size() == 0) return;
        if (clientsMap.entrySet().stream().allMatch(entry -> entry.getValue().size() == 0)) return;
        Enumeration<String> keys = clientsMap.keys();
        while (keys.hasMoreElements()) {
            String key = keys.nextElement();
            try {
                List<String> children = curatorClient.getChildren().forPath("/" + key);
                for (String child : children) {
                    String childPath = "/" + key + "/" + child;
                    byte[] bytes = curatorClient.getData().forPath(childPath);
                    String content = new String(bytes);
                    if (!content.equals("0 0")) {
                        String[] arr = content.split(" ");
                        String requestDate = arr[0];
                        Long requestLong = Long.valueOf(requestDate);
                        long currentLong = System.currentTimeMillis();
                        long passedLong = currentLong - requestLong;
                        if (passedLong > 5000L) {
                            curatorClient.setData().forPath(childPath, "0 0".getBytes());
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("=============执行了job");
    }
}
